﻿using System;
using System.Text;

namespace Utils.liangshui.hex
{
    public class ByteUtils
    {

        private const String ALL_HEX = "0123456789ABCDEF";
        
        /// <summary>
        /// 16进制字符串转字节数组
        /// 比如： 1a02
        /// </summary>
        /// <param name="hexStrParam"></param>
        /// <returns></returns>
        public static byte[] hexStrToByteArr(String hexStrParam)
        {
            String hexStr = hexStrParam.ToUpper();//转换成大写
            if (String.IsNullOrEmpty(hexStr))
            {
                return null;
            }

            if (hexStr.Length % 2 != 0)
            {
                hexStr = "0" + hexStr;
            }

            int len = hexStr.Length / 2;
            byte[] resArr = new byte[len];
            int j = 0;
            for (int i = 0; i < len; i++)
            {
                char c1 = hexStr[j];
                char c2 = hexStr[j + 1];
                byte b1 = (byte)ALL_HEX.IndexOf(c1);
                byte b2 = (byte)ALL_HEX.IndexOf(c2);
                b1 = (byte)(b1 << 4);
                resArr[i] = (byte) ((b1 | b2) & 0xff);
                j = j + 2;
            }
            return resArr;
        }


        /// <summary>
        /// 字节数组转字符串
        /// </summary>
        /// <param name="arrParam"></param>
        /// <returns></returns>
        public static String byteArrToHexStr(byte[] arrParam)
        {
            if (arrParam == null || arrParam.Length == 0)
            {
                return "";
            }
            byte[] arr = arrParam;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < arr.Length; i++)
            {
                byte b = arr[i];
                byte b1 = (byte) ((b >> 4) & 0x0f);
                byte b2 = (byte) (b & 0x0f);
                sb.Append(ALL_HEX[b1]);
                sb.Append(ALL_HEX[b2]);
            }
            return sb.ToString().ToUpper();
        }
        
    }
}